const AJAX = getApp().ajax,
      $wx = getApp().$wx,
      getColor = getApp().globalData.getColor;

Page({
  data:{
    getColor: getColor(),
    isPayment: false,
    showRA: false,
    deliveryTime: [[],[]],
    pickerVal: [0,0],
    column_1: 0,
    column_2: 0,
    deliveryInfo: { status: 0},
    deliverStatus: ['立即送达','指定配送'],
    remarkInfo: null,
    paymentType: {
      balanceMoney: 1,
      WeCahtMoney: 2
    }
  },

  onLoad(options){
    $wx.setNavColor(getColor().val);

    if(options.order_id){
      this.setData({
        orderId: options.order_id
      });
    }
    this.getDeliveryTime();    
  },

  onShow(){
    this.getAddList();
  },

  onShareAppMessage(){
  },

  // 立即支付
  ImmediatePayment(){
    let td = this.data;
    
    if (td.orderInfo.add[0]){
      this.setData({
        isPayment: true
      });
    }else{
      $wx.showToast('请选择收货地址');
    }
  },

  // 设置默认收货地址
  setDefaultAddresss(){
    this.setData({
      showRA: true
    });
  },

  // 收货地址
  RASelected(e){
    let address_info = e.detail.itemData;

    if (address_info.is_default  == 2){
      this.setDefaultAddress({
        id: address_info.id,
        is_default: 1
      });
    }
  },

  // 编辑收货地址
  RACompile(e){
    let address_id = e.detail.itemData.id;

    wx.navigateTo({
      url: `/pages/other-pages/compile-address/compile-address?address_id=${address_id}`,
    })
  },

  // 加载失败回调
  loadFailedCallback(){
    console.log('yes');
  },

  // 删除地址
  deleteAddress(id) {
    let _this = this;

    AJAX.deleteAddress({ id }, (status, data, msg) => {
      if (status) {
        _this.setData({
          slidingDeleteActive: false
        });
        _this.getAddList();
      } else {
        $wx.showToast(msg);
      }
    });
  },

  // 监听滑动
  columnChange(e) { 
    let td = this.data, detail = e.detail;

    if (detail.column == 0) {
      this.setData({
        column_1: detail.value,
        column_2: 0
      });
      td.deliveryTime[1] = td.DeliveryTimeInfo[td.column_1].time;
      
    } else if (detail.column == 1){
      this.setData({
        column_2: detail.value
      });
    }

    this.setData({
      deliveryTime: td.deliveryTime,
      pickerVal: [td.column_1, td.column_2]
    });
  },

  // 获取配送时间
  getColumnChange(e){
    let td = this.data, detail = e.detail.value;

    this.setData({
      deliveryInfo: {
        status: detail[0] == 0 && detail[1] == 0 ? 0 : 1,
        day: td.DeliveryTimeInfo[detail[0]].day,
        mouthDay: td.DeliveryTimeInfo[detail[0]].mouthDay,
        time: td.DeliveryTimeInfo[detail[0]].time[detail[1]]
      }
    });
  },
  
  // 备注
  remarkInput(e){
    let val = e.detail.value;

    this.setData({
      remarkInfo: val
    });
  },

  // 确认支付
  paymentConfirm(e){
    let _this = this, td = _this.data, 
        payment_info = e.detail.payment;
        
    if (!payment_info.type){
      $wx.showToast('请选择支付方式');
    }else{
      AJAX.addOrder({
        pay_type: td.paymentType[payment_info.type],
        deliver_time: td.deliveryInfo.day + ' ' + td.deliveryInfo.time,
        address_id: td.orderInfo.add[0].id,
        price: td.orderInfo.car_total_price,
        order_id: td.orderId || null,
        is_immediately: td.deliveryInfo.status + 1,
        remark: td.remarkInfo
      }, (status, data, msg) => {
        if (status) {
          _this.payOrder({
            pay_type: data.pay_type,
            order_id: data.order_id
          });
        } else {
          $wx.showToast(msg);
        }
      });
    }
  },

  /*获取地址列表*/
  getAddList() {
    let _this = this;

    AJAX.getAddList({}, (status, data, msg) => {
      if (status) {
        _this.setData({
          addressList: data || []
        });

        _this.createOrder();
      } else {
        $wx.showToast(msg);
      }
    });
  },

  /**
   * 设置默认地址
   * @param id
   * @param is_default
   * */ 
  setDefaultAddress(params = {}){
    let _this = this;
    
    AJAX.setDefaultAddress(params, (status, data, msg)=>{
      if(status){
        _this.getAddList();
      }else{
        $wx.showToast(msg);
      }
    });
  },

  /*创建订单*/
  createOrder() {
    let _this = this, td = _this.data;
    wx.showNavigationBarLoading();
    
    AJAX.createOrder({
      order_id: td.orderId || null
    }, (status, data, msg) => {
      wx.hideNavigationBarLoading();
      if(status){
        _this.setData({
          orderInfo: data
        });
      }else{
        $wx.showToast(msg);
      }
    });
  },

  //配送时间
  deliveryTime(){
    this.getDeliveryTime();
  },

  /*获取配送时间*/
  getDeliveryTime(params = {}){
    let _this = this, td = _this.data;
    wx.showLoading({
      title: '加载中...',
      mask: true
    });

    AJAX.getDeliveryTime(params, (status, data, msg) => {
      wx.hideLoading();
      if (status) {
        data.forEach(item => {
          td.deliveryTime[0].push(item.mouthDay);
        });
        td.deliveryTime[1] = data[0].time;

        _this.setData({
          DeliveryTimeInfo: data,
          deliveryTime: td.deliveryTime,
          deliveryInfo: {
            status: 0,
            day: data[0].day,
            mouthDay: data[0].mouthDay,
            time: data[0].time[0]
          }
        });
      }
    });
  },

  /**
   * 支付
   * @param pay_type
   * @param order_id
   * */ 
  payOrder(params = {}){
    let _this = this;
    wx.showLoading({
      title: '支付中...'
    });
    
    AJAX.payOrder(params, (status, data, msg)=>{
      wx.hideLoading();
      
      if(status){
        if (params.pay_type == 1){
          $wx.showToast(msg);
         
          setTimeout(callBack => {
            wx.redirectTo({
              url: '/pages/other-pages/order-detail/order-detail?order_id=' + data.order_id,
              success() {
                _this.setData({
                  isPayment: false
                });
              }
            });
          }, 1500);
        } else if (params.pay_type == 2){
          wx.requestPayment({
            timeStamp: data.timeStamp,
            nonceStr: data.nonceStr,
            package: data.package,
            signType: data.signType,
            paySign: data.paySign,
            success(res) {
              $wx.showToast('支付成功');

              setTimeout(callBack => {
                wx.redirectTo({
                  url: '/pages/other-pages/order-detail/order-detail?order_id=' + data.order_id,
                  success() {
                    _this.setData({
                      isPayment: false
                    });
                  }
                });
              }, 1500);
            },
            fail(res) {
              $wx.showToast('支付失败');
              setTimeout(callBack => {
                wx.redirectTo({
                  url: '/pages/other-pages/order-detail/order-detail?order_id=' + data.order_id,
                  success() {
                    _this.setData({
                      isPayment: false
                    });
                  }
                });
              }, 1500);
            }
          });
        }
      }else{
        $wx.showToast(msg);
      }
    });
  }
  
});